package com.fuyun.microservice.connect;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;

@Slf4j
public class SslContextFactory {
    private static SSLContext serverContext;
    private static final String PROTOCOL = "TLS";

    public static SSLContext getServerContext(@NotNull String pkPath, String storePass, String keyPass) {
        if (serverContext != null) {
            return serverContext;
        }
        InputStream in = null;
        try {
            //密钥库KeyStore
            KeyStore ks = KeyStore.getInstance("JKS");
            //加载服务端证书
            ClassPathResource classPathResource = new ClassPathResource(pkPath.replace("classpath:/", ""));
            in = classPathResource.getInputStream();
            ks.load(in, storePass.toCharArray());
            KeyManagerFactory  kmf = KeyManagerFactory.getInstance("SunX509");
            //初始化密钥管理器, keypass 指定别名条目的密码(私钥的密码)
            kmf.init(ks, keyPass.toCharArray());

            //获取安全套接字协议（TLS协议）的对象
            serverContext = SSLContext.getInstance(PROTOCOL);
            //参数一：认证的密钥   参数二：对等信任认证，如果双向认证就写成tf.getTrustManagers(),参数三：伪随机数生成器 。 由于单向认证，服务端不用验证客户端，所以第二个参数为null
            serverContext.init(kmf.getKeyManagers(), null, null);
        } catch (Exception e) {
            throw new Error("Failed to init the server-side SSLContext", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("close InputStream error", e);
                }
            }
        }
        return serverContext;
    }


}
